package com.dpf.hou.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dpf.hou.mapper.NoticeMapper;
import com.dpf.hou.pojo.Notice;
import com.dpf.hou.service.NoticeService;
import com.dpf.hou.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@CrossOrigin
@RestController
@RequestMapping("notice")
public class NoticeController {
    @Autowired
    private NoticeMapper noticeMapper;
    @Autowired
    private NoticeService noticeService;
    @GetMapping("getNoticePage")
    public Page<Notice> getNoticePage(int page,int size){
        return noticeService.getNoticePage(page,size);
    }

    @PostMapping("upload")
    public ResultUtil upload(MultipartFile uploadFile) {
//声明上传地址
        String path = "d://upload";
//判断上传地址是否存在，如果不存在，要创建
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
//获取上传的文件名
        String fileName = UUID.randomUUID()+uploadFile.getOriginalFilename();
//创建新的文件对象
        File newFile = new File(file, fileName);
//将新的文件对象放到指定位置
        try {
            uploadFile.transferTo(newFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        ResultUtil resultUtil = null;
//返回给前端当前上传的文件在文件服务器上的地址
        String url = "http://localhost:8888/upload/"+fileName;
//返回给前端当前上传的是图片还是视频
        if (fileName.endsWith("jpg") || fileName.endsWith("png") ||
                fileName.endsWith("gif") || fileName.endsWith("jpeg")) {
//是图片
            resultUtil = new ResultUtil(1,"图片上传成功",url);
        } else {
//是视频
            resultUtil = new ResultUtil(2,"视频上传成功",url);
        }
        return resultUtil;
    }

    @PostMapping("addNotice")
    public boolean addNotice(Notice notice){
        return noticeService.addNotice(notice);
    }

    @DeleteMapping("delNotice")
    public boolean delNotice(Integer nid){
        return noticeMapper.deleteById(nid);
    }

}
